package com.qianyanglong.apifox.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONReader.Feature;

public class Application {
	
	public static void main(String[] args) {
		String params1 = args[1];
		Set<String> fileterKey = new HashSet<String>(Arrays.asList("signKey", "startTime", "endTime"));
		String params2 = args[2];
		JSONArray array = JSONArray.parseArray(params2, Feature.IgnoreSetNullValue);
		String requestData = array.stream().map(obj->(JSONObject)obj).filter(json->{
			return fileterKey.contains(json.getString("key"));
		}).map(json->{
			return json.getString("key")+"="+json.getString("value");
		}).collect(Collectors.joining("&"));
		try {
			Signature sign = Signature.getInstance("SHA256withRSA");
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(params1));
			PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
			sign.initSign(privateKey);
		    sign.update(requestData.getBytes());
		    System.out.println(URLEncoder.encode(Base64.getEncoder().encodeToString(sign.sign()),"UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SignatureException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
